package com.example.music_player_app.ui.playListDetail;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.music_player_app.Bean.SongDetail;
import com.example.music_player_app.R;
import com.example.music_player_app.api.service.playList.PlayListDetailService;
import com.example.music_player_app.api.service.playList.SearchService;
import com.example.music_player_app.api.service.playList.SongDetailService;
import com.example.music_player_app.ui.home.MyAdapter;
import com.example.music_player_app.utils.ApiServer;
import com.example.music_player_app.utils.CookieServer;

import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PlayListDetail extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView textView; // 歌单名
    private List<SongDetail> songList = new ArrayList<>(); // 歌单信息
    private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_list_detail);

        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("data");
        Bundle bundle1 = intent.getBundleExtra("searchData");

        toolbar = findViewById(R.id.tool_bar);
        textView = findViewById(R.id.play_list_id);
        listView = findViewById(R.id.song_list_view);

        try {
            if (bundle1 != null && bundle1.getBoolean("isSearch", false)) {
                toolbar.setTitle("搜索详情");
                textView.setText("搜索：" + bundle1.getString("searchQuery"));
                initSearchList(bundle1.getString("searchQuery"), 30); //初始化搜索列表
            }
            toolbar.setTitle("歌单详情");
            Long playListId = bundle.getLong("id");
            initPlayListDetail(playListId); // 初始化歌单歌曲列表
        } catch (Exception e) {
            e.printStackTrace();
        }


        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

    }

    private void initSearchList(String searchQuery, int i) {
        new Thread(){
            @Override
            public void run() {
                ApiServer http = new ApiServer();
                SearchService searchService = http.getRetrofit().create(SearchService.class);
                Call<ResponseBody> call = searchService.get(CookieServer.getCookie(), searchQuery, i);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            JSONObject jsonObject = (JSONObject) JSONObject.parse(response.body().string());
                            JSONObject jsonObject1 = jsonObject.getJSONObject("result");
                            JSONArray array = jsonObject1.getJSONArray("songs");
                            JSONObject res;

                            for (int i=0;i<array.size();i++){
                                SongDetail songDetail = new SongDetail();
                                res = array.getJSONObject(i);
                                System.out.println(res);
                                songDetail.setId(Long.parseLong(res.getString("id"))); // 歌曲ID
                                songDetail.setName(res.getString("name")); // 歌名

                                JSONArray singerArray = res.getJSONArray("ar"); // 获取歌手
                                songDetail.setSinger(singerArray.getJSONObject(0).getString("name"));

                                JSONObject jsonObject2 = res.getJSONObject("al"); // 获取歌曲图片
                                songDetail.setSongImgUrl(jsonObject2.getString("picUrl"));

                                songList.add(songDetail);
                            }
                            listView.setAdapter(new MySongAdapter(songList, PlayListDetail.this));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.i("fail", "onFailure: " + t);
                    }
                });
            }
        }.start();
    }

    private void initPlayListDetail(Long playListId) {
        new Thread(){
            @Override
            public void run() {
                ApiServer http = new ApiServer();
                PlayListDetailService playListDetailService = http.getRetrofit().create(PlayListDetailService.class);
                Call<ResponseBody> call = playListDetailService.get(CookieServer.getCookie(), playListId);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            JSONObject jsonObject = (JSONObject) JSONObject.parse(response.body().string());
                            JSONObject jsonObject2 = jsonObject.getJSONObject("playlist");

                            textView.setText(jsonObject2.getString("name"));

                            JSONArray array = jsonObject2.getJSONArray("trackIds");

                            String song_ids = ""; // 拼接song的id，请求到song的详细信息
                            for(int i=0;i<array.size();i++) {
                                JSONObject res = array.getJSONObject(i);
                                if(i == array.size()-1) {
                                    song_ids = song_ids + res.getString("id");
                                }else {
                                    song_ids = song_ids + res.getString("id") + ",";
                                }
                            }
                            initSongList(song_ids);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.i("fail", "onFailure: " + t);
                    }
                });
            }
        }.start();
    }

    private void initSongList(String song_ids) {
        new Thread(){
            @Override
            public void run() {
                ApiServer http = new ApiServer();
                SongDetailService songDetailService = http.getRetrofit().create(SongDetailService.class);
                Call<ResponseBody> call = songDetailService.get(CookieServer.getCookie(), song_ids);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            JSONObject jsonObject = (JSONObject) JSONObject.parse(response.body().string());
                            JSONArray array = jsonObject.getJSONArray("songs");
                            JSONObject res;

                            for (int i=0;i<array.size();i++){
                                SongDetail songDetail = new SongDetail();
                                res = array.getJSONObject(i);
                                songDetail.setId(Long.parseLong(res.getString("id"))); // 歌曲ID
                                songDetail.setName(res.getString("name")); // 歌名

                                JSONArray singerArray = res.getJSONArray("ar"); // 获取歌手
                                songDetail.setSinger(singerArray.getJSONObject(0).getString("name"));

                                JSONObject jsonObject1 = res.getJSONObject("al"); // 获取歌曲图片
                                songDetail.setSongImgUrl(jsonObject1.getString("picUrl"));

                                songList.add(songDetail);
                            }
                            listView.setAdapter(new MySongAdapter(songList, PlayListDetail.this));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.i("fail", "onFailure: " + t);
                    }
                });
            }
        }.start();
    }
}